package com.giser.testapp;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.Gson;
import com.giser.testapp.lib.App.EnvApplication;
import com.giser.testapp.lib.App.GlobClass;
import com.giser.testapp.lib.Download.MyDownloadListenter;
import com.giser.testapp.lib.Extern.CacheEngine;
import com.giser.testapp.lib.Extern.DiskCache;
import com.giser.testapp.lib.Extern.PicEntity;
import com.giser.testapp.lib.Extern.PicTakeUtil;
import com.giser.testapp.lib.JavaScript.ParamInfo;
import com.giser.testapp.lib.JavaScript.UserTag;
import com.giser.testapp.lib.Tool.AlertUtil;
import com.giser.testapp.lib.Tool.CleanDataUtil;
import com.giser.testapp.lib.Tool.EnvLog;
import com.giser.testapp.lib.Tool.PhoneStateUtil;
import com.giser.testapp.lib.Tool.ToastUtil;
import com.giser.testapp.lib.sHA1;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import static com.giser.testapp.lib.App.GlobClass.APP_CACAHE_DIRNAME;

public class MainActivity extends CheckPermissionsActivity {

    protected BridgeWebView webView;
    private ProgressBar progressBar;
    private ImageView imgView;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> uploadMessage;
    private List<String> recordPhotoList=null;
    private Gson gson=new Gson();
    private PicEntity pic=new PicEntity();
    private JSONArray picArray = null;
    private int picTag=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        EnvApplication.getApplication().minContext=MainActivity.this;
        initView();
        DiskCache.getInstance().open(getApplicationContext());
        EnvLog.i("sd="+ sHA1.getsHA1(this));
    }
    //页面初始化
    private void initView(){
        webView= (BridgeWebView) findViewById(R.id.webView);
        progressBar= (ProgressBar) findViewById(R.id.progressBar);
        imgView=(ImageView)findViewById(R.id.imageView);
        imgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                checkNetWork();
            }
        });
        checkNetWork();
    }
    //检测网络
    private void checkNetWork(){
        if(PhoneStateUtil.isNetworkConnected(this)){
            imgView.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
            initWebView();
        }else{
            imgView.setVisibility(View.VISIBLE);
            webView.setVisibility(View.GONE);
        }
    }
    //初始化webView
    private void initWebView() {
        //支持获取手势焦点
        webView.requestFocusFromTouch();
        WebSettings setting = webView.getSettings();
        //支持Js
        setting.setJavaScriptEnabled(true);
        setting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存

        //setting.setCacheMode(WebSettings.LOAD_DEFAULT);//缓存模式
        //是否支持画面缩放，默认不支持
        setting.setBuiltInZoomControls(true);//支持缩放，默认为true。是下面那个的前提。
        setting.setSupportZoom(true);//设置内置的缩放控件。
        //是否显示缩放图标，默认显示
        setting.setDisplayZoomControls(false);//隐藏原生的缩放控件
        //设置网页内容自适应屏幕大小
//        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setUseWideViewPort(true); //将图片调整到适合webview的大小
        setting.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        setting.supportMultipleWindows(); //多窗口
        setting.setAllowFileAccess(true);//设置可以访问文件
        setting.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
        setting.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        setting.setLoadsImagesAutomatically(true);  //支持自动加载图片
        setting.setDefaultTextEncodingName("utf-8");//设置编码格式
        //是否允许在WebView中访问内容URL（Content Url），默认允许。内容Url访问允许WebView从安装在系统中的内容提供者载入内容。
        setting.setAllowContentAccess(true);

        //启用地理定位
        //setting.setGeolocationEnabled(true);
        //设置定位的数据库路径
        //最重要的方法，一定要设置，这就是出不来的主要原因
        // 开启 DOM storage API 功能
        setting.setDomStorageEnabled(true);
        //setting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        //开启 database storage API 功能
        setting.setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath()+ APP_CACAHE_DIRNAME;
        //设置  Application Caches 缓存目录
        setting.setAppCachePath(cacheDirPath);
        //应用缓存API是否可用，默认值false, 结合setAppCachePath(String)使用。
        //开启 Application Caches 功能
        setting.setAppCacheEnabled(true);

        setting.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= 21) {
            setting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.loadUrl(GlobClass.webViewUrl);
          /* webView.loadUrl("file:///android_asset/a.html");*/
        //webView.addJavascriptInterface(new WebAppInterface(this,mHandler),"Android");
        webView.setWebChromeClient(new MyWebChromeClient());
        //给webview加入下载监听事件
        webView.setDownloadListener(new MyDownloadListenter());
        webViewEvent();
        webView.setWebViewClient(new MyWebViewClient(webView));
    }

    private void webViewEvent(){
       /* webView.registerHandler("submitFromWeb", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                EnvLog.i("data="+data);
                startPictureService();
                EnvLog.i("handler = submitFromWeb, data from web = " + data);
                function.onCallBack("submitFromWeb exe, response data from Java");
            }
        });*/
        webView.setDefaultHandler(new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
               // Log.e(TAG, "DefaultHandler接收全部来自web的数据："+data);
                EnvLog.i("data="+data);
                ParamInfo param=new Gson().fromJson(data,ParamInfo.class);
                switch (param.getAction()){
                    case "getPic":
                        startPictureService();
                        break;
                    case "getLoc":
                        getLocationInfo();
                        break;
                    case "getOpenGaoDe":
                        getOpenGaoDe(param.getValue());
                        break;
                    case "getScanCode":
                        getScanCode();
                        break;
                    case "login":
                        //多个tag用#隔开
                        initLogin(param.getValue().toString());
                        break;
                    case "closeApp":
                        AlertUtil.createDialog_Exit(MainActivity.this);
                        break;
                    case "clearCache":
                        clearWebViewCache();
                        break;
                    case "goBack":
                        goBack();
                        break;
                    case "getCache":
                        String cacheSize="0";
                        try {
                            cacheSize=CleanDataUtil.getTotalCacheSize(getApplicationContext());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        function.onCallBack(cacheSize);
                        break;
                    default:
                        break;
                }
               // function.onCallBack("DefaultHandler收到Web发来的数据，回传数据给你");
            }
        });
    }

    //Web视图
    private class MyWebViewClient extends BridgeWebViewClient {
        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, final String url) {
            String key = "http://localhost";
            final WebResourceResponse[] response = {null};
            if(url.contains(key)){
                String imgPath = url.replace(key,"");
                CacheEngine.getInstance().getLocalImgInMain(imgPath)
                        .subscribe(new Action1<byte[]>() {
                            @Override
                            public void call(byte[] bytes) {
                                response[0] = new WebResourceResponse("image/png", "UTF-8", new ByteArrayInputStream(bytes));
                            }
                        });
                return response[0];
            }else {
                return super.shouldInterceptRequest(view, url);
            }
        }
        @Override
        public void  onPageStarted(WebView view, String url, Bitmap favicon) {
            //设定加载开始的操作
            //疑问：传入权限信息
            super.onPageStarted(view,url,favicon);
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            //设定加载结束的操作
            super.onPageFinished(view,url);
        }
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
            EnvLog.i("onReceivedSslError");
        }
        @Override
        public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
            switch(errorCode)
            {
                case GlobClass.HttpStatus_SC_NOT_FOUND:
                    EnvLog.i("error");
                    // view.loadUrl("file:///android_assets/error_handle.html");
                    break;
            }
            super.onReceivedError(view,errorCode,description,failingUrl);
        }
    }

    //WebChromeClient
    private class MyWebChromeClient extends WebChromeClient{
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress != 100) {
                progressBar.setProgress(newProgress);
            } else {
                progressBar.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            setTitle(title);
        }

        //API18+
        public boolean onConsoleMessage(ConsoleMessage cm) {
            EnvLog.i(cm.message());
           /* Log.d("MyApplication", cm.message() + " -- From line "
                    + cm.lineNumber() + " of "
                    + cm.sourceId() );*/
            return true;
        }

        @Override
        public void onCloseWindow(WebView window) {
            //finish();
            super.onCloseWindow(window);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(MainActivity.this).setTitle("提示信息").setMessage(message)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    }).setCancelable(false).create().show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(MainActivity.this).setTitle("提示信息").setMessage(message)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            }).setCancelable(false).create().show();
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            // 处理JS 的调用逻辑
            result.confirm();
            return true;
        }

        // For Android 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), GlobClass.FILE_SELECT_CODE);
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            startActivityForResult(Intent.createChooser(i, "File Browser"), GlobClass.FILE_SELECT_CODE);
        }

        // For Android >4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), GlobClass.FILE_SELECT_CODE);
        }
        // For Lollipop 5.0+ Devices
        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
        {
            if (Build.VERSION.SDK_INT >= 21){
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = fileChooserParams.createIntent();
                try
                {
                    startActivityForResult(intent, GlobClass.FILE_SELECT_CODE_V5);
                } catch (ActivityNotFoundException e)
                {
                    uploadMessage = null;
                    Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                    return false;
                }
            }
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,GeolocationPermissions.Callback callback)
        { callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
    }

    //调用本地图片服务
    private void startPictureService(){
        PicTakeUtil util = new PicTakeUtil(this);
        util.takePicture(new IHandlerCallBack() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(List<String> photoList) {
               // picListAdapter(photoList);
                adapter(photoList);
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onError() {

            }
        });
    }

    public void responseLocInfo(String locInfo){
        EnvLog.i("responseLocInfo="+locInfo);
        webView.callHandler("setLoc",locInfo,new CallBackFunction(){
            @Override
            public void onCallBack(String data) {
                EnvLog.i("loc 来自web的回传数据：" + data);
            }
        });
    }

    //返回图片路径 回调JavaScript
    private void picListAdapter(List<String> photoList) {
        Gson gson=new Gson();
        PicEntity pic=new PicEntity();
        JSONArray picArray = new JSONArray();
        for(int i=0;i<photoList.size();i++){
            pic.setPicPath("http://localhost"+photoList.get(i));
            EnvLog.i("pic sing="+pic.getPicPath());
            String picStr = gson.toJson(pic);
            JSONObject picObject;
            try {
                picObject = new JSONObject(picStr);
                picArray.put(i, picObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        webView.callHandler("setImgPic",picArray.toString(),new CallBackFunction(){
            @Override
            public void onCallBack(String data) {
                EnvLog.i("img 来自web的回传数据：" + data);
            }
        });
    }

    //打开高德
    private void getOpenGaoDe(String data){
        EnvLog.i("getOpenGaoDe");
        if (isInstallByread("com.autonavi.minimap")) {
            //跳转处理
            //单独导航
//            String amapuri = "amapuri://route/plan/?dlat=39.98848272&dlon=116.47560823&dev=0&t=0";
            String amapuri = "amapuri://route/plan/?dev=0&t=0&";
            String _amapuri= amapuri.concat(data);
            Intent intent = new Intent("android.intent.action.VIEW",
                    android.net.Uri.parse(_amapuri));
            intent.setPackage("com.autonavi.minimap");
            startActivity(intent);

        }else {
            Toast.makeText(MainActivity.this,"未安装该应用",Toast.LENGTH_LONG).show();
        }
    }
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    //扫描二维码
    private void getScanCode(){
        EnvLog.i("getScanCode");
        doScanCode();
//        webView.callHandler("setScanCode","setScanCode",new CallBackFunction(){
//            @Override
//            public void onCallBack(String data) {
//                EnvLog.i("ScanCode 来自web的回传数据：" + data);
//            }
//        });
    }

    private void doScanCode(){
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        /*ZxingConfig是配置类  可以设置是否显示底部布局，闪光灯，相册，是否播放提示音  震动等动能
         * 也可以不传这个参数
         * 不传的话  默认都为默认不震动  其他都为true
         * */

        //ZxingConfig config = new ZxingConfig();
        //config.setShowbottomLayout(true);//底部布局（包括闪光灯和相册）
        //config.setPlayBeep(true);//是否播放提示音
        //config.setShake(true);//是否震动
        //config.setShowAlbum(true);//是否显示相册
        //config.setShowFlashLight(true);//是否显示闪光灯
        //intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, GlobClass.REQUEST_CODE_SCAN);
    }

    private Handler handler_post = new Handler();
    //获取位置信息
    private void getLocationInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler_post.post(new Runnable() {
                    @Override
                    public void run() {
                        EnvLog.i("getLocationInfo...");
                        EnvApplication.getApplication().getLocationServer(MainActivity.this).getLocationModule();
                    }
                });
            }
        }).start();
    }

    private void getSettingLocationInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler_post.post(new Runnable() {
                    @Override
                    public void run() {
                        EnvApplication.getApplication().getLocationServer(MainActivity.this).updateGpsSetting();
                    }
                });
            }
        }).start();
    }

    // flipscreen not loading again
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    //页面回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        EnvLog.i("resultCode="+resultCode);
        EnvLog.i("requestCode="+requestCode);
        /*if (resultCode != RESULT_OK) {
            return;
        }*/
        switch (requestCode) {
            case GlobClass.FILE_SELECT_CODE :
                EnvLog.i("FILE_SELECT_CODE");
                if (null == mUploadMessage)
                    return;
                if(null==data){
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage=null;
                }else{
                    Uri uri = data.getData();
                    mUploadMessage.onReceiveValue(uri);
                    mUploadMessage = null;
                }
                break;
            case GlobClass.FILE_SELECT_CODE_V5:
                EnvLog.i("FILE_SELECT_CODE_V5");
                if (uploadMessage == null)
                    return;
                if(data==null){
                    uploadMessage.onReceiveValue(null);
                    uploadMessage=null;
                }else{
                    ArrayList<String> resultList=data.getStringArrayListExtra("data");
                    if (Build.VERSION.SDK_INT >= 21){
                        uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode,data));
                    }
                    uploadMessage = null;

                }
                break;
            case GlobClass.SELECT_PIC_CODE:
                EnvLog.i("SELECT_PIC_CODE");
                String path = selectImage(this, data);
                break;
            case GlobClass.CAPTURE_IMAGE_CODE:
                EnvLog.i("CAPTURE_IMAGE_CODE");
                if(data != null){
                    if(data.hasExtra("data")){
                        Bitmap thunbnail = data.getParcelableExtra("data");
                        //处理缩略图
                    }
                }else{
                    EnvLog.i("dfsfe");
                }
                break;
            case GlobClass.SetGPS_CODE:
                EnvLog.i("SetGPS_CODE");
               // getLocationInfo();
                getSettingLocationInfo();
                break;
            case GlobClass.CheckPermission_CODE:
                EnvLog.i("CheckPermission_CODE....");
                isNeedCheck=true;
                break;
            case GlobClass.REQUEST_CODE_SCAN:
                super.onActivityResult(requestCode, resultCode, data);
                if (data != null) {
                    String content = data.getStringExtra(Constant.CODED_CONTENT);
                    webView.callHandler("setScanCode",content,new CallBackFunction(){
                        @Override
                        public void onCallBack(String data) {
                            EnvLog.i("ScanCode 来自web的回传数据：" + data);
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    private void setJPush(UserTag userTag){
        EnvLog.i(userTag.getUserID());
        JPushInterface.setAlias(getApplicationContext(),1,userTag.getUserID());

        Set<String> tagSet = new LinkedHashSet<String>();
        String tags=userTag.getGroupTag();
        String[] tagList=tags.split("#");
        for(int i=0;i<tagList.length;i++){
            tagSet.add(tagList[i]);
            EnvLog.i(tagList[i]);
        }
        JPushInterface.setTags(getApplicationContext(),1,tagSet);
    }
    //获取本地图片的路径
    public static String selectImage(Context context, Intent data){
        Uri selectedImage = data.getData();
        if(selectedImage!=null){
            String uriStr=selectedImage.toString();
            String path=uriStr.substring(10,uriStr.length());
            if(path.startsWith("com.sec.android.gallery3d")){
                return null;
            }
        }
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }

    //导航网页浏览历史
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /*if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())  {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            } else {
                finish();
            }
        }*/
        if((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
            webView.callHandler("navCtrl",null,new CallBackFunction(){
                @Override
                public void onCallBack(String data) {
                    EnvLog.i("img 来自web的回传数据：" + data);
                }
            });
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        JPushInterface.onResume(getApplicationContext());
        String mess=getIntent().getStringExtra(GlobClass.PushMessage);
        if(mess!=null && mess.length()>0){
            webView.callHandler("setPushInfo",mess,new CallBackFunction(){
                @Override
                public void onCallBack(String data) {
                   // EnvLog.i("onresume data="+data);
                }
            });
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        JPushInterface.onPause(getApplicationContext());
    }

    private void adapter(List<String> photoList) {
        recordPhotoList=photoList;
        picTag=0;
        picArray=new JSONArray();
        CacheEngine.getInstance().getLocalImgsMany2(photoList)
                .flatMap(new Func1<byte[], Observable<String>>() {
                    @Override
                    public Observable<String> call(byte[] bytes) {
                        return byte2base64(bytes);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        sendToH5(s);
                    }
                });
    }

    private void sendToH5(String s) {
        if(null!=recordPhotoList){
            pic.setPicPath("data:image/png;base64," + s );
            try {
                picArray.put(new JSONObject(gson.toJson(pic)));
                picTag++;
                if(picTag==recordPhotoList.size()){
                    if(picArray.length()>0){
                        webView.callHandler("setImgPic",picArray.toString(),new CallBackFunction(){
                            @Override
                            public void onCallBack(String data) {
                                EnvLog.i("img 来自web的回传数据：" + data);
                            }
                        });
                    }
                    recordPhotoList.clear();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public Observable<String> byte2base64(final byte[] bytes) {
        return
                Observable.create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        String s = Base64.encodeToString(bytes, Base64.NO_WRAP);
                        subscriber.onNext(s);
                    }
                }).subscribeOn(Schedulers.newThread());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EnvApplication.getApplication().getLocationServer(MainActivity.this).destroyLocation();
    }

    /**
     * 清除WebView缓存
     */
    public void clearWebViewCache(){

        CleanDataUtil.clearAllCache(getApplicationContext());
        ToastUtil.showShort(this,"缓存已清理");
    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {
        //EnvLog.i("delete file path=" + file.getAbsolutePath());
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            //EnvLog.i("delete file no exists " + file.getAbsolutePath());
        }
    }

    //返回上一层
    private void goBack(){
        if (webView.canGoBack()) {
           // EnvLog.i("keyi goBack");
            webView.goBack();
        }
       // EnvLog.i("no goBack");
    }

    //注册推送信息
    public void initLogin(String param){
        final String paramStr=param;
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler_post.post(new Runnable() {
                    @Override
                    public void run() {
                        // EnvApplication.getLocationInfo(MainActivity.this).getLocationInfo();
                        UserTag userTag=new Gson().fromJson(paramStr,UserTag.class);
                        setJPush(userTag);
                    }
                });
            }
        }).start();
    }

    @Override
    protected  void onNewIntent(Intent intent){
        super.onNewIntent(intent);
        setIntent(intent);
    }
}
